package com.aifast.gen.business.controller;

import com.aifast.common.annotations.AiIdempotent;
import com.aifast.common.base.Controller;
import com.aifast.common.base.R;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.gen.business.entity.GenTable;
import com.aifast.gen.business.entity.GenTableColumn;
import com.aifast.gen.business.service.GenTableService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 代码生成业务表 前端控制器
 * </p>
 *
 * @author fujian
 * @since 2022-05-23
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/gen/genTable")
public class GenTableController extends Controller {

    private final GenTableService service;

    @GetMapping("list")
    public LayuiDataTable list() {
        return service.list(getSearchValue(), getPage());
    }

    @GetMapping("tableColumnList")
    public LayuiDataTable tableColumnList() {
        return service.tableColumnList(getInt("tableId"),getPage());
    }

    @AiIdempotent
    @PostMapping("add")
    public R add(GenTable genTable) {
        return service.insertOrUpdate(genTable) ? OK() : ERROR();
    }

    @GetMapping("info")
    public R info() {
        return service.info(getInt("id"));
    }

    @AiIdempotent
    @GetMapping("del")
    public R del() {
        return service.del(getInt("id"), get("ids")) ? OK() : ERROR();
    }

    @GetMapping("dbList")
    public LayuiDataTable dbList(){
        return service.dbList(getSearchValue(),getPage());
    }

    @GetMapping("import")
    public R importTable (){
        return service.insertByTableName(getStrArray("tableNames"));
    }


    @GetMapping("genCode")
    public Object genCode() {
        service.genCode(get("tableName"), request);
        return OK();
    }

    @GetMapping("download")
    public void download() throws IOException {
        byte[] data = service.downloadCode(get("tableName"));
        genCode(response,data);
    }
    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ai3.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    @GetMapping("preview")
    public R preview(){
        return OK(service.preview(getLong("tableId")));
    }

    @PostMapping("eidtTableColumn")
    public R eidtTableColumn(GenTableColumn column){
        return service.eidtTableColumn(column) ? OK() : ERROR();
    }

}

